package cn.wm.e_02.solve03_FixedLengthFrameDecoder;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.Arrays;
import java.util.Collections;
import java.util.concurrent.atomic.AtomicInteger;

public class TimeClientHandler extends ChannelInboundHandlerAdapter {

    private AtomicInteger counter = new AtomicInteger(0);

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        /**
         * 连续发送 10 条数据
         */
        for (int i = 0; i < 10; i++) {
            /** DelimiterBasedFrameDecoder 解码器自定义的分隔符是 "$_"，所以发送消息时要在结尾处加上*/
            String reqMsg = "QUERY TIME ORDER";
            byte[] reqMsgByte = reqMsg.getBytes("UTF-8");
            byte[] result = new byte[64];
            System.arraycopy(reqMsgByte,0,result,0,reqMsgByte.length);
            /** writeBytes：将指定的源数组的数据传输到缓冲区
             * 调用 ChannelHandlerContext 的 writeAndFlush 方法将消息发送给服务器*/
            ByteBuf reqByteBuf = Unpooled.copiedBuffer(result);
            /** 每次发送的同时进行刷新*/
            ctx.writeAndFlush(reqByteBuf);
        }
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        String body = (String) msg;
        System.out.println(body+"--------"+counter.getAndIncrement());
    }

    /**
     * 当发生异常时，打印异常 日志，释放客户端资源
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        /**释放资源*/
        ctx.close();
    }
}
